//index.js
//获取应用实例
const app = getApp()
import {
  getToken,
  userLogin
} from '../../api/login.js'
Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    rules: [{
      name: 'userName',
      rules: {
        required: true,
        message: '请输入用户名'
      },
    }, {
      name: 'password',
      rules: {
        required: true,
        message: '请输入密码'
      },
    }],
    error: null,
    form: {
      userName: null,
      password: null,
    },
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  bindViewTap2: function() {
    wx.navigateTo({
      url: '../crawlList1/crawlList1',
    })
  },
  onLoad: function(options) {
    console.log('当前页面', getCurrentPages())
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.setData({
                userInfo: res.userInfo,
                hasUserInfo: true
              })
            }
          })
        }
      }
    })

  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  // 输入事件
  formInputChange(e) {
    const {
      field
    } = e.currentTarget.dataset
    this.setData({
      [`form.${field}`]: e.detail.value
    })
  },
  login() {
    console.log(this.selectComponent('#ruleForm'))
    this.selectComponent('#ruleForm').validate((valid, errors) => {
      console.log('valid', valid, errors)
      if (!valid) {
        const firstError = Object.keys(errors)
        if (firstError.length) {
          this.setData({
            error: errors[firstError[0]].message
          })

        }
      } else {
        getToken(this.data.form.userName, this.data.form.password).then(res => {
          wx.setStorage({
            key: "token",
            data: res.data
          })
          userLogin().then(res => {
            wx.setStorage({
              key: "user",
              data: JSON.stringify(res.data.basicUser)
            })
            wx.navigateTo({
              url: '/pages/crawlList/crawlList',
            })
          }).catch(err => {

          })
        }).catch(err => {

        })
      }
    })
  },
})